#include "GameObject.h"
#include "ASprite.h"
#include "game.h"

int GameObject::sRandomID = 9999;
GameObject::GameObject()
{
	m_doTrackContactList=true;
	m_bIntersectionListRemoveEvent = false;
	m_physicsBody = NULL;
	SetObjectType(Object_None);	
	m_objectID = sRandomID++;

	m_speedUnit = 0;

	SetEnabled(true);
	SetRenderable(true);

	m_flags.NeedDespawn = false;
}
	
GameObject::~GameObject()
{
	if ( m_physicsBody )
	{
		GetGameObjectManager()->GetPhysicsWorld().DestroyBody( m_physicsBody );
	}
}


void GameObject::SaveData(CWriteFile* stream)
{
	stream->WriteS32(m_objectID);
	stream->write(&m_flags,sizeof(m_flags));


	
}
void GameObject::LoadData(CReadFile* stream)
{
	ASSERT(m_objectID == stream->ReadS32());
	stream->read(&m_flags,sizeof(m_flags));
	
}


void GameObject::AddContact( GameObject* h )
{
	if(this->GetObjectType() == Object_Balloon)
	{
		int gfgf=0;
	}
	if ( m_doTrackContactList )
	{
		bool bExit = false;
		for(int i =0;i<m_contactList.size();i++)
		{
			if(m_contactList[i] == h)
			{
				bExit = true;
				break;
			}
		}
		if ( ! bExit )
		{
			m_contactList.push_back( h );
		}
	}

}

void GameObject::AddCollision( GameObject* h, const b2Vec2& position, const b2Vec2& normal, float impulseMagnitude )
{	
	if(this->GetObjectType() == Object_Balloon)
	{
		int gfgf=0;
	}
	//if ( m_doTrackCollisionList )
	{
		Contact c;
		c.obj = h;
		c.position = position;
		c.normal = normal;
		c.magnitude = impulseMagnitude;
		m_collisionList.push_back(c);
	}
}

void GameObject::MasterUpdate_PreCollision()
{
	if ( IsUpdatable() )
	{
		Update_PreCollision();
	}
}

void GameObject::SetPosition(float x, float y)
{
	if(m_physicsBody)
	{
		m_physicsBody->SetXForm(b2Vec2(x,y),0);
	}
}
void GameObject::SetSpeed(const b2Vec2& v)
{
	if(m_physicsBody)
	{
		m_physicsBody->SetLinearVelocity(v);
	}
}

void GameObject::SetEnabled( bool v )
{

	if(v != m_flags.Enabled)
	{
		m_flags.Enabled = v;
		//OnEnabledChanged (v);
		if(v)
		{
			InitPhysics();
		}
		else
		{
			if(m_physicsBody)
				GetGameObjectManager()->GetPhysicsWorld().DestroyBody(m_physicsBody);
		}
	}

	//Refresh2DCollision();
}

void GameObject::Draw()
{
	
}

void GameObject::Update()
{
	m_contactList.clear();
	m_collisionList.clear();

}

void GameObject::LoadParams(IAttributes* attr)
{
	m_objectID = attr->getAttributeAsInt("Id");
	Load(attr);
}
